package com.yssoft.service.production;

import com.google.common.collect.Lists;
import com.yssoft.entity.inventory.TOutstockApply;
import com.yssoft.entity.inventory.TOutstockApplyDetail;
import com.yssoft.entity.production.TCollarMaterial;
import com.yssoft.entity.production.TCollarMaterialDetail;
import com.yssoft.entity.production.TPackageCode;
import com.yssoft.entity.production.TWorksheet;
import com.yssoft.mapper.core.TDdDetailMapper;
import com.yssoft.mapper.production.TCollarMaterialDetailMapper;
import com.yssoft.mapper.production.TCollarMaterialMapper;
import com.yssoft.mapper.production.TMaterialRecordMapper;
import com.yssoft.mapper.production.TPackageCodeMapper;
import com.yssoft.mapper.inventory.TOutstockApplyDetailMapper;
import com.yssoft.mapper.inventory.TOutstockApplyMapper;
import com.yssoft.mapper.inventory.TWarehouseMapper;
import com.yssoft.mapper.production.TWorksheetMapper;
import com.yssoft.utils.AppUserHelper;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @类名称: IntoProductionService
 * @类描述: 生产投产service
 * @作者: 洪丰
 * @创建时间:2018年5月9日 上午11:34:58
 */
@Service
public class IntoProductionService {
    
    @Resource
    private TWorksheetMapper worksheetMapper;
    @Resource
    private TCollarMaterialDetailMapper collarMaterialDetailMapper;
    @Resource
    private TCollarMaterialMapper collarMaterialMapper;
    @Resource
    private TPackageCodeMapper packageCodeMapper;
    @Resource
    private TDdDetailMapper ddDetailMapper;
    @Resource
    private TMaterialRecordMapper materialRecordMapper;
    @Resource
    private TWarehouseMapper warehouseMapper;
    @Resource
    private TOutstockApplyMapper outstockApplyMapper;
    @Resource
    private TOutstockApplyDetailMapper outstockApplyDetailMapper;
    
    /**
     * @方法名称: findPage
     * @功能描述: 获取加工单列表
     * @作者: 洪丰
     * @创建时间:2018年5月9日 上午11:39:40
     * @param page
     * @param limit
     * @param companyId
     * @param productName
     * @param processStat
     * @param createTime 
     * @return List<Map<String,Object>>
     */
    public List<Map<String, Object>> findPage(int page, int limit, int companyId, String productName, String processStat, Integer batchId, String createTime) {
        HashMap<String,Object> param = new HashMap<>();
        param.put("productName",productName);
        param.put("processStat",processStat);
        param.put("companyId",companyId);
        param.put("batchId",batchId);
        param.put("createTime",createTime);
        int start = ((page - 1) * limit);
		int end = limit;
		param.put("start", start);
		param.put("end", end);
		List<Map<String, Object>>  worksheetList = worksheetMapper.selectWorksheetPage(param);
        return worksheetList;
    }
    /**
     * @方法名称: findPage1
     * @功能描述: 获取加工单列表
     * @作者: 王永宁
     * @创建时间:2018年6月6日 下午9:39:40
     * @param page
     * @param limit
     * @param companyId
     * @param productName
     * @param processStat
     * @param createTime 
     * @return List<Map<String,Object>>
     */
    public List<Map<String, Object>> findPage1(int page, int limit, int companyId, String productName, String processStat, Integer batchId, String createTime) {
    	HashMap<String,Object> param = new HashMap<>();
    	param.put("productName",productName);
    	param.put("processStat",processStat);
    	param.put("companyId",companyId);
    	param.put("batchId",batchId);
    	param.put("createTime",createTime);
    	int start = ((page - 1) * limit);
    	int end = limit;
    	param.put("start", start);
    	param.put("end", end);
    	List<Map<String, Object>>  worksheetList = worksheetMapper.selectWorksheetPage1(param);
    	return worksheetList;
    }
    
    /**
     * @方法名称: findWorksheetDetail
     * @功能描述: 查看加工详细
     * @作者: 洪丰
     * @创建时间:2018年5月9日 下午1:44:21
     * @param id
     * @return Map<String,Object>
     */
    public Map<String, Object> findWorksheetDetail(Integer id) {
    	Map<String, Object> workSheetEntity = worksheetMapper.selectWorksheetDetail(id);
		List<Map<String, Object>>  collarlList = collarMaterialMapper.selectCollarMaterialQuantity(id);
		List<Map<String, Object>>  sfgcollarlList = collarMaterialMapper.selectSfgQuantity(id);
		Map<String,Object> workSheet = new HashMap<>();
		workSheet.put("workSheetEntity", workSheetEntity);
		workSheet.put("collarlList", collarlList);
		workSheet.put("sfgcollarlList", sfgcollarlList);
        return workSheet;
    }
        
    /**
     * @方法名称: save
     * @功能描述: 保存领料
     * @作者: 洪丰
     * @创建时间:2018年5月9日 下午2:34:55
     * @param request
     * @param entity void
     */
    public void save (HttpServletRequest request,String tWorksheeId, String[] tMaterialId, String[] createCode, String[] quantity, String[] tWarehouseId, String[] mType){
    	TWorksheet ws = worksheetMapper.selectByPrimaryKey(Integer.parseInt(tWorksheeId));
    	
    	TCollarMaterial entity = new TCollarMaterial();
    	entity.settWorksheeId(Integer.parseInt(tWorksheeId));
    	String code = "LL" + Calendar.getInstance().getTimeInMillis();
		entity.setDeleteFlag("0");
		entity.setCode(code);
		entity.setCreateTime(new Date());
		entity.setCreatorId(AppUserHelper.getCurrentUserId(request));
		entity.setCreatorName(AppUserHelper.getCurrentUserName(request));
		entity.settEId(AppUserHelper.getCurrentCompanyId(request));
		entity.setDeptId(AppUserHelper.getCurrentDeptId(request));
		entity.setDeptName(AppUserHelper.getCurrentDeptName(request));
		
		collarMaterialMapper.insert(entity);
		Boolean isAllZero = false;
		List<TOutstockApply> oaList = Lists.newArrayList();
		
		for(int i = 0; i < tMaterialId.length; i++){
			if("0".equals(quantity[i])){
				continue;
			}else{
				isAllZero = true;
			}
			TCollarMaterialDetail cmdEntity = new TCollarMaterialDetail();
			cmdEntity.settCMaterialId(entity.getId());
			cmdEntity.settMaterialId(Integer.parseInt(tMaterialId[i]));
			if(null != createCode && !"".equals(createCode)){
				cmdEntity.setIsCreateCode(createCode[i]);
			}
			Integer warehouseId = Integer.parseInt(tWarehouseId[i]);
			cmdEntity.settWarehouseId(warehouseId);
			cmdEntity.setQuantity(new BigDecimal(quantity[i]));
			
			cmdEntity.settEId(AppUserHelper.getCurrentCompanyId(request));
			cmdEntity.setDeleteFlag("0");
			cmdEntity.setCreateTime(new Date());
			cmdEntity.setCreatorId(AppUserHelper.getCurrentUserId(request));
			cmdEntity.setCreatorName(AppUserHelper.getCurrentUserName(request));
			cmdEntity.settEId(AppUserHelper.getCurrentCompanyId(request));
			cmdEntity.setDeptId(AppUserHelper.getCurrentDeptId(request));
			cmdEntity.setDeptName(AppUserHelper.getCurrentDeptName(request));
			//来源类型：1-物料 2-半成品
			cmdEntity.setType(mType[i]);
			
			collarMaterialDetailMapper.insert(cmdEntity);
			
			//生成出库申请单
			boolean isNew = false;
			for(TOutstockApply oldOaEntity : oaList){
				//申请单已存在，只需要新建出库申请明细
				if(oldOaEntity.gettWarehouseId().compareTo(warehouseId) == 0 ){
					isNew = true;
					TOutstockApplyDetail newOad = new TOutstockApplyDetail();
					
					newOad.setCreateTime(new Date());
					newOad.setDeleteFlag("0");
					newOad.setCreatorId(AppUserHelper.getCurrentUserId(request));
					newOad.setCreatorName(AppUserHelper.getCurrentUserName(request));
					newOad.settEId(AppUserHelper.getCurrentCompanyId(request));
					newOad.setDeptId(AppUserHelper.getCurrentDeptId(request));
					newOad.setDeptName(AppUserHelper.getCurrentDeptName(request));
					
					//1-成品 2-半成品 3-物料
					if(mType[i].equals("1")){
						newOad.setpType("3");
						newOad.settMId(cmdEntity.gettMaterialId());
					}else{
						newOad.setpType("2");
						newOad.settSgId(cmdEntity.gettMaterialId());
					}
					
					newOad.setQuantity(cmdEntity.getQuantity());
					//来源类型：1-生产 2-采购 3-销售
					newOad.setSourceType("1");
					//出库状态：1-待出库 2-已出库
					newOad.setStat("1");
					//来源id：根据类型，判断关联领料明细或销货明细
					newOad.settSourceId(cmdEntity.getId());
					newOad.settWarehouseId(cmdEntity.gettWarehouseId());
					newOad.settOutstockAppId(oldOaEntity.getId());
					this.outstockApplyDetailMapper.insert(newOad);
				}
			}
			
			//新建出库申请接单和出库申请明细
			if(!isNew){
				TOutstockApply newOaEntity = new TOutstockApply();
				String oaCode = "CKS" + Calendar.getInstance().getTimeInMillis();
				newOaEntity.setCode(oaCode);
				
				newOaEntity.setCreateTime(new Date());
				newOaEntity.setDeleteFlag("0");
				newOaEntity.setCreatorId(AppUserHelper.getCurrentUserId(request));
				newOaEntity.setCreatorName(AppUserHelper.getCurrentUserName(request));
				newOaEntity.settEId(AppUserHelper.getCurrentCompanyId(request));
				newOaEntity.setDeptId(AppUserHelper.getCurrentDeptId(request));
				newOaEntity.setDeptName(AppUserHelper.getCurrentDeptName(request));
				
				//来源类型：1-生产 2-采购 3-销售
				newOaEntity.setSourceType("1");
				//出库状态：1-待出库 2-已出库
				newOaEntity.setStat("1");
				//来源id：根据类型，判断关联加工单或收货单
				newOaEntity.settSourceId(Integer.parseInt(tWorksheeId));
				newOaEntity.settWarehouseId(warehouseId);
				newOaEntity.setDeliveryDate(new Date());
				this.outstockApplyMapper.insert(newOaEntity);
				
				oaList.add(newOaEntity);
				
				TOutstockApplyDetail newOad = new TOutstockApplyDetail();
				
				newOad.setCreateTime(new Date());
				newOad.setDeleteFlag("0");
				newOad.setCreatorId(AppUserHelper.getCurrentUserId(request));
				newOad.setCreatorName(AppUserHelper.getCurrentUserName(request));
				newOad.settEId(AppUserHelper.getCurrentCompanyId(request));
				newOad.setDeptId(AppUserHelper.getCurrentDeptId(request));
				newOad.setDeptName(AppUserHelper.getCurrentDeptName(request));
				
				//1-成品 2-半成品 3-物料
				if(mType[i].equals("1")){
					newOad.setpType("3");
					newOad.settMId(cmdEntity.gettMaterialId());
				}else{
					newOad.setpType("2");
					newOad.settSgId(cmdEntity.gettMaterialId());
				}
				
				newOad.setQuantity(cmdEntity.getQuantity());
				//来源类型：1-生产 2-采购 3-销售
				newOad.setSourceType("1");
				//出库状态：1-待出库 2-已出库
				newOad.setStat("1");
				//来源id：根据类型，判断关联领料明细或销货明细
				newOad.settSourceId(cmdEntity.getId());
				newOad.settWarehouseId(cmdEntity.gettWarehouseId());
				newOad.settOutstockAppId(newOaEntity.getId());
				this.outstockApplyDetailMapper.insert(newOad);
			}
			
			//保存包装码
			if("1".equals(cmdEntity.getIsCreateCode())){
				Map<String, Object> proMap = collarMaterialMapper.selectProByWorksheetId(Integer.parseInt(tWorksheeId));
				if(null != proMap.get("traceability_type") && proMap.get("traceability_type").equals("1")){
					for(int j = 0; j < cmdEntity.getQuantity().intValue(); j++){
						String bcode = "B" + Calendar.getInstance().getTimeInMillis();
						TPackageCode pcEntity = new TPackageCode();
						pcEntity.setCode(bcode);
						pcEntity.settCMaterialDId(cmdEntity.getId());
						pcEntity.settWorksheeId(entity.gettWorksheeId());
						pcEntity.setLabelStat("0");
						
						pcEntity.settEId(AppUserHelper.getCurrentCompanyId(request));
						pcEntity.setDeleteFlag("0");
						pcEntity.setCreateTime(new Date());
						pcEntity.setCreatorId(AppUserHelper.getCurrentUserId(request));
						pcEntity.setCreatorName(AppUserHelper.getCurrentUserName(request));
						pcEntity.settEId(AppUserHelper.getCurrentCompanyId(request));
						pcEntity.setDeptId(AppUserHelper.getCurrentDeptId(request));
						pcEntity.setDeptName(AppUserHelper.getCurrentDeptName(request));
						pcEntity.setQuantity(0);
						//生成包装码暂时不用
						/*String url = MakeEncode.barEncode(bcode);
						pcEntity.setUrl(url);
						pcEntity.setTurl(url);*/
						
						packageCodeMapper.insert(pcEntity);
					}
				}
			}
		}
		if(isAllZero && "0".equals(ws.getProcessStat())){
			TWorksheet newWs = new TWorksheet();
			newWs.setProcessStat("1");
			newWs.setId(ws.getId());
			worksheetMapper.updateByPrimaryKeySelective(newWs);
		}
    }
    
    /**
     * @方法名称: toCollarMaterial
     * @功能描述: 通过加工单id获取该产品的物料列表
     * @作者: 洪丰
     * @创建时间:2018年5月9日 下午5:00:19
     * @param id
     * @param companyId
     * @return List<Map<String,Object>>
     */
    public List<Map<String, Object>> toCollarMaterial(Integer id, Integer companyId) {
    	//获取原料父类
    	List<Map<String, Object>> materialClassilylList = ddDetailMapper.selectMaterialDdDetail();
    	for(Map<String, Object> materialClassify : materialClassilylList){
    		HashMap<String,Object> param = new HashMap<>();
            param.put("worksheetId",id);
    		param.put("dId",materialClassify.get("id"));
    		//获取物料
    		List<Map<String, Object>> mrList = materialRecordMapper.selectMaterialByworksheetId(param);
    		materialClassify.put("mrList", mrList);
    		
    		//获取仓库
    		HashMap<String,Object> whparam = new HashMap<>();
    		whparam.put("cId",materialClassify.get("id"));
    		whparam.put("companyId",companyId);
    		List<Map<String, Object>> warehouseList = warehouseMapper.selectWarehouseByCId(whparam);
    		materialClassify.put("warehouseList", warehouseList);
    	}
    	Map<String, Object> sfgMap = new HashMap<String, Object>();
    	sfgMap.put("name", "半成品");
    	HashMap<String,Object> sfgparam = new HashMap<>();
    	sfgparam.put("worksheetId",id);
    	List<Map<String, Object>> mrList = materialRecordMapper.selectSfgByworksheetId(sfgparam);
    	sfgMap.put("mrList", mrList);
    	List<Map<String, Object>> sfgWarehouseList = warehouseMapper.selectSfgWarehouseByCId(companyId);
    	sfgMap.put("warehouseList", sfgWarehouseList);
    	materialClassilylList.add(sfgMap);
    	
        return materialClassilylList;
    }
    
    /**
     * @方法名称: findCollarMaterialPage
     * @功能描述: 获取领料单及明细信息
     * @作者: 洪丰
     * @创建时间:2018年5月9日 下午6:47:33
     * @param page
     * @param limit
     * @param worksheeId
     * @param cmDate
     * @return List<Map<String,Object>>
     */
    public List<Map<String, Object>> findCollarMaterialPage(int page, int limit, int worksheetId, String cmDate) {
        HashMap<String,Object> param = new HashMap<>();
        param.put("cmDate",cmDate);
        param.put("worksheeId",worksheetId);
        int start = ((page - 1) * limit);
		int end = limit;
		param.put("start", start);
		param.put("end", end);
		List<Map<String, Object>> collarMaterialList = collarMaterialMapper.selectCollarMaterialList(param);
		for(Map<String, Object> cmEtnity : collarMaterialList){
			List<Map<String, Object>> detailList = 
					collarMaterialDetailMapper.selectCollarMaterialDetailLsit(Integer.parseInt(cmEtnity.get("id").toString()));
			cmEtnity.put("detailList", detailList);
		}
        return collarMaterialList;
    }
    
    /**
     * @方法名称: findPackageCode
     * @功能描述: 根据领料明细单id获取包装码列表
     * @作者: 洪丰
     * @创建时间:2018年5月9日 下午7:03:28
     * @param page
     * @param limit
     * @param collarMaterialDetailId
     * @return List<Map<String,Object>>
     */
    public List<Map<String, Object>> findPackageCode(int page, int limit, int collarMaterialDetailId) {
        HashMap<String,Object> param = new HashMap<>();
        param.put("cmdId",collarMaterialDetailId);
        int start = ((page - 1) * limit);
		int end = limit;
		param.put("start", start);
		param.put("end", end);
		List<Map<String, Object>> packageCodeList = packageCodeMapper.selectPackageCodeByCMDid(param);
        return packageCodeList;
    }

}


